//
//  ByIndexVC.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/10.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByIndexVC.h"

// vc
#import "ByMemberStoreVC.h"             // 会员储值
#import "ByStoreCollectionVC.h"         // 储值卡收款
#import "ByScanCodeVC.h"                // 扫码收款
#import "ByOrderVC.h"                   // 订单
#import "ByDayEarningVC.h"              // 当日收益
#import "ByReleaseGoodsNewVC.h"         // 发布商品
#import "ByIndexConfirmSuccessVC.h"     // 验码成功

// view
#import "ByViewIndexCancel.h"           // 注销
#import "ByViewIndexLoginAfter.h"       // 登录后动画
// location
#import "ByCoreToolLocation.h"          // 定义服务


@interface ByIndexVC ()<UITextFieldDelegate,ByCoreLoactionDelegate>
@property (nonatomic, strong) UIScrollView  *scroll;

@property (nonatomic, strong) UITextField   *certifyTextField;
@property (nonatomic, strong) UILabel       *cityLabel;
@property (nonatomic, strong) ByViewIndexLoginAfter *afterView; // 登陆后动画
@end

@implementation ByIndexVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"佳慧超市";
    [self addBYItemviews:@[@"注销"] mode:ByNavigationItemModeImageAndText position:ByNavigationItemPositionModeRight];
    // 展示动画
    [self needShowLoginAfter];
    
    [self createCityLocationView];
    [self createViews];
    [self location];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)rightItemsAction:(NSInteger)rightIndex{
    [ByCoreToolAlert showOnlyText:@"注销"];
    ByViewIndexCancel *cancelView = [[ByViewIndexCancel alloc] init];
    [cancelView show];
}
// 是否需要展示登录后动画
#define KIsFirstUse @"isFirstUse"
- (BOOL)needShowLoginAfter{
    
    NSNumber *isFirstUse = [ByCoreCacheSqlite3 getValueWithKey:KIsFirstUse];
    // 没有设置过值，就说明是第一次
    if ( isFirstUse == nil) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_after(dispatch_time(0, NSEC_PER_SEC * 0.5), dispatch_get_main_queue(), ^{
                [self.afterView show];
            });
        });
        [ByCoreCacheSqlite3 setObjectWithKey:KIsFirstUse value:@YES];
        return YES;
    } else {
        return NO;
    }
    
}
#pragma mark - getter
- (UIScrollView *)scroll{
    if (!_scroll) {
        _scroll = [[UIScrollView alloc] init];
        _scroll.backgroundColor = BY_TABLE_COLOR;
        [self.view addSubview:_scroll];
        [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            if (@available(iOS 11.0, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-49);
            }else{
                make.top.equalTo(self.view.mas_top);
                make.bottom.equalTo(self.view.mas_bottom).offset(- 49);
            }
        }];
        _scroll.showsVerticalScrollIndicator = NO;
        _scroll.bounces = NO;

    }
    return _scroll;
}

- (ByViewIndexLoginAfter *)afterView{
    if (!_afterView) {
        _afterView = [[ByViewIndexLoginAfter alloc] init];
    }
    return _afterView;
}

#pragma mark - 创建视图
// 创建导航栏视图
- (void)createCityLocationView {
    CGFloat margin = 5;
    UIControl *locationView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 0, 44)];
    [locationView addTarget:self action:@selector(locationTap) forControlEvents:UIControlEventTouchUpInside];
    // 图片
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    imgView.image = [UIImage imageNamed:@"Index_location"];
    // 文字
    self.cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [@"定位" getSizeOfString:12].width, 20)];
    self.cityLabel.font = FONT(12);
    self.cityLabel.text = @"定位";
    self.cityLabel.textAlignment = NSTextAlignmentCenter;
    self.cityLabel.textColor = [UIColor whiteColor];
    
    [locationView addSubview:imgView];
    [locationView addSubview:self.cityLabel];
    
    locationView.width = MAX(imgView.width, self.cityLabel.width);
    
    // 设置位置
    CGFloat remainY = locationView.height - imgView.height - self.cityLabel.height - margin;
    imgView.top = remainY / 2;
    imgView.x = locationView.width / 2;
    self.cityLabel.top = imgView.bottom + margin;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:locationView];
    self.navigationItem.leftBarButtonItem = leftItem;

}

- (void)createViews{
    // 验码
    CGFloat height;
    if (@available(iOS 11.0,*)) {
        height = (SCREEN_HEIGHT - self.view.safeAreaInsets.bottom - 49) / 6;
    }else{
        height = (SCREEN_HEIGHT - 49) / 6;
    }
    UIView *certifyView = [[UIView alloc] init];
    certifyView.backgroundColor = BY_THEME_COLOR;
    [self.scroll addSubview:certifyView];
    [certifyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scroll.mas_top);
        make.left.equalTo(self.scroll.mas_left);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, height));
    }];
    
    _certifyTextField = [[UITextField alloc] init];
    [certifyView addSubview:_certifyTextField];
    [_certifyTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(certifyView.mas_left).offset(45);
        make.top.equalTo(certifyView.mas_top).offset((height - 50) / 2);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 90, 50));
    }];
    _certifyTextField.placeholder = @"验码";
    _certifyTextField.textAlignment = NSTextAlignmentCenter;
    _certifyTextField.backgroundColor = [UIColor whiteColor];
    _certifyTextField.textColor = [UIColor darkGrayColor];
    _certifyTextField.layer.cornerRadius = 4.0;
    _certifyTextField.font = FONT(24);
    _certifyTextField.delegate = self;
    
    // 当日收益
    UIView *shouyiView = [[UIView alloc] init];
    shouyiView.backgroundColor = BY_TABLE_COLOR;
    [self.scroll addSubview:shouyiView];
    [shouyiView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(certifyView.mas_bottom);
        make.left.equalTo(self.scroll.mas_left);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, height));
    }];
    
    UILabel *shouyiLabel = [[UILabel alloc] init];
    [shouyiView addSubview:shouyiLabel];
    [shouyiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(shouyiView.mas_left).offset(10);
        make.top.equalTo(shouyiView.mas_top).offset(10);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 20, 20));
    }];
    shouyiLabel.textColor = [UIColor lightGrayColor];
    shouyiLabel.text = @"当日收益：";
    shouyiLabel.font = FONT(16);
    
    UILabel *moneyLabel = [[UILabel alloc] init];
    moneyLabel.textAlignment = NSTextAlignmentCenter;
    moneyLabel.font = FONT(30);
    [shouyiView addSubview:moneyLabel];
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(shouyiLabel.mas_bottom).offset(10);
        make.left.equalTo(shouyiView.mas_left).offset(10 + 40);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 20 - 40 - 40, 40));
    }];
    
    UIImageView *arrowImg = [[UIImageView alloc] init];
    [shouyiView addSubview:arrowImg];
    [arrowImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(moneyLabel.mas_top);
        make.left.equalTo(moneyLabel.mas_right);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    arrowImg.image = [UIImage imageNamed:@"Index_arrow_right"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(DayEarningAction)];
    shouyiView.userInteractionEnabled = YES;
    [shouyiView addGestureRecognizer:tap];
    
    //  会员总数 + 共享会员
    UIView *infoView = [[UIView alloc] init];
    infoView.backgroundColor = [UIColor whiteColor];
    [self.scroll addSubview:infoView];
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(shouyiView.mas_bottom);
        make.left.equalTo(shouyiView.mas_left);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, height - 30));
    }];
    
    CGFloat y = (height - 30 - 45) / 2;
    UILabel *totalLabel = [[UILabel alloc] init];
    [infoView addSubview:totalLabel];
    [totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(infoView.mas_top).offset(y);
        make.left.equalTo(infoView.mas_left).offset(10);
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH / 2 - 20), 20));
    }];
    totalLabel.font = FONT(16);
    totalLabel.textAlignment = NSTextAlignmentCenter;
    
    
    UILabel *totalInfoLabel = [[UILabel alloc] init];
    [infoView addSubview:totalInfoLabel];
    [totalInfoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(totalLabel.mas_bottom).offset(5);
        make.left.equalTo(totalLabel.mas_left);
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH / 2 - 20), 20));
    }];
    totalInfoLabel.textAlignment = NSTextAlignmentCenter;
    totalInfoLabel.font = FONT(16);
    totalInfoLabel.textColor = [UIColor lightGrayColor];
    totalInfoLabel.text = @"会员总数（人）";
    
    UIView *lineView = [[UIView alloc] init];
    [infoView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(totalInfoLabel.mas_right).offset(10);
        make.top.equalTo(infoView.mas_top).offset(15);
        make.size.mas_equalTo(CGSizeMake(1, height - 60));
    }];
    lineView.backgroundColor = [UIColor lightGrayColor];
    
    UILabel *shareLabel = [[UILabel alloc] init];
    [infoView addSubview:shareLabel];
    [shareLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineView.mas_right).offset(10);
        make.top.equalTo(totalLabel.mas_top);
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH / 2 - 20), 20));
    }];
    shareLabel.font = FONT(16);
    shareLabel.textAlignment = NSTextAlignmentCenter;
    
    UILabel *shareInfoLabel = [[UILabel alloc] init];
    [infoView addSubview:shareInfoLabel];
    [shareInfoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(shareLabel.mas_left);
        make.top.equalTo(shareLabel.mas_bottom).offset(5);
        make.size.mas_equalTo(CGSizeMake((SCREEN_WIDTH / 2 - 20), 20));
    }];
    shareInfoLabel.text = @"共享会员（人）";
    shareInfoLabel.textAlignment = NSTextAlignmentCenter;
    shareInfoLabel.font = FONT(16);
    shareInfoLabel.textColor = [UIColor lightGrayColor];
    
    
    // 功能模块
    UIView *functionView = [[UIView alloc] init];
    [self.scroll addSubview:functionView];
    [functionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(infoView.mas_bottom);
        make.left.equalTo(self.scroll.mas_left);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, height * 2 + 30));
    }];
    
    NSArray *funcArray = @[@"会员储值",@"储值卡收款",@"扫码收款",@"订单"];
    CGFloat margin = 10,left = 20,x;
    for (int i = 0; i < funcArray.count; i ++) {
        CGFloat width = (SCREEN_WIDTH - left * 2 - margin) / 2;
        x = left + (i % 2) * (width + margin);
        y = (i / 2) * (height + margin) + margin;
        UIControl *bgControl = [[UIControl alloc] init];
        bgControl.layer.cornerRadius = 10.0;
        bgControl.layer.borderColor = BY_THEME_COLOR.CGColor;
        bgControl.layer.borderWidth = 3;
        bgControl.layer.masksToBounds = YES;
        bgControl.backgroundColor = [UIColor colorWithR:224 g:141 b:42];
        bgControl.tag = 10 + i;
        [functionView addSubview:bgControl];
        [bgControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(functionView.mas_top).offset(y);
            make.left.equalTo(functionView.mas_left).offset(x);
            make.size.mas_equalTo(CGSizeMake(width, height));
        }];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        [bgControl addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(bgControl.mas_top).offset((height - 30) / 2);
            make.left.equalTo(bgControl.mas_left);
            make.size.mas_equalTo(CGSizeMake(width, 30));
        }];
        titleLabel.font = B_FONT(16);
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = funcArray[i];
        
        
        [bgControl addTarget:self action:@selector(fuction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    CGFloat width = [@"发布商品" getSizeOfString:16].width + 30;
    UIButton *releaseButton = [[UIButton alloc] init];
    releaseButton.backgroundColor = [UIColor whiteColor];
    [functionView addSubview:releaseButton];
    [releaseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(functionView.mas_centerY);
        make.centerX.equalTo(functionView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(width, width));
    }];
    releaseButton.layer.cornerRadius = width / 2;
    releaseButton.layer.borderWidth = 3;
    releaseButton.layer.borderColor = [UIColor colorWithR:239 g:197 b:143].CGColor;
    [releaseButton setTitle:@"发布商品" forState:UIControlStateNormal];
    [releaseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    releaseButton.titleLabel.font = FONT(16);
    [releaseButton addTarget:self action:@selector(releaseAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 广告位
    UIView *testView = [[UIView alloc] init];
    testView.backgroundColor = BY_THEME_COLOR;
    [self.scroll addSubview:testView];
    [testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(functionView.mas_bottom);
        make.left.equalTo(functionView.mas_left);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, height));
        make.bottom.equalTo(self.scroll.mas_bottom);
    }];
    // 我的测试数据
    moneyLabel.text = @"¥ 3600.00";
    totalLabel.text = @"5323";
    shareLabel.text = @"33454";

}

#pragma mark - 点击事件
// 当日收益
- (void)DayEarningAction{
    ByDayEarningVC *vc = [[ByDayEarningVC alloc] init];
    [self by_normalPush:vc hasNavi:YES];
}

// 模块功能
- (void)fuction:(UIControl *) control{
    NSLog(@"%ld",(long)control.tag);
    switch (control.tag - 10) {
        case 0:{
            ByMemberStoreVC *vc = [[ByMemberStoreVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
        }
            break;
        case 1:{
            ByStoreCollectionVC *vc = [[ByStoreCollectionVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
        }
            break;
        case 2:{
            ByScanCodeVC *vc = [[ByScanCodeVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
        }
            break;
        case 3:{
            ByOrderVC *vc = [[ByOrderVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
        }
            break;
        default:
            break;
    }
}

// 发布商品
- (void)releaseAction:(UIButton *)button{
    ByReleaseGoodsNewVC *vc = [[ByReleaseGoodsNewVC alloc] init];
    [self by_normalPush:vc hasNavi:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.text.length == 5) {
        [self confirmSuccess];
        return NO;
    }
    return YES;
}

// 验码成功
- (void)confirmSuccess{
    _certifyTextField.text = @"";
    ByIndexConfirmSuccessVC *vc = [[ByIndexConfirmSuccessVC alloc] init];
    [self by_normalPush:vc hasNavi:YES];
}

// 定位
- (void)locationTap{
    
}
#pragma mark - 定位
- (void)location {
    
//    [ByCoreToolAlert showLoadind:@"正在定位..."];
    ByCoreToolLocation *locationManager = [ByCoreToolLocation shareInstance];
    locationManager.delegate = self;
    [locationManager configLocationService];
    [locationManager startUpdateLoaction];
}
- (void)locationDidComplete:(NSDictionary *)placeInfoDic {
    
    [ByCoreToolAlert hideHud];
    
    // 更新当前显示的城市
//    _city = placeInfoDic[@"city"];
//    [self updateLocation];
//
//    // 设置定位城市
//    BY_APPDELEGATE.locationCity = _city;
//    BY_APPDELEGATE.locationDic = placeInfoDic;
    
}
- (void)locationDidFail:(NSError *)error {
    [ByCoreToolAlert showOnlyText:@"定位失败"];
}
- (void)updateLocation {
    
//    UILabel *cityLabel = [self.locationView viewWithTag:2];
//    cityLabel.text = _city;
}

@end
